package com.ting.rss;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.ting.rss.model.NewsInfo;
import com.ting.rss.util.Init;
import com.ting.rss.util.Prop;

public class RssActivity extends ListActivity {

	/** Called when the activity is first created. */

	public static ArrayList<NewsInfo> newsList;
	public static int state = DownloadAsyncTask.UPLOAD_FINISHED;

	private TextView title;
	private ImageView fresh;

	private int i=0;
	// private TextView text;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(Prop.mainLayout);

		title = (TextView) findViewById(R.id.title);
		fresh = (ImageView) findViewById(R.id.fresh);
		registerForContextMenu(title);
		fresh.setOnClickListener(new FreshListener());
		
		getInfo(false);
		
		if(Init.share.getBoolean("firstTime", true)){
			Init.editor.putBoolean("firstTime", false);
			showDialog(3);
		}
		
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if(i==1){
			menu.add(0, 0, 0, "GOD MODE");
		}else {
			Toast.makeText(this, "亲，上帝模式小幅度更新哦，找找吧...", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Prop.setGodMode(true);
		return true;

	}

	class FreshListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Prop.shake.vibrate(25);
			getInfo(true);

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, "刷新");
		menu.add(0, 2, 2, "夜间模式");
		menu.add(0, 3, 3, "设置");
		menu.add(0, 4, 4, "关于");
		menu.add(0, 5, 5, "退出");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 5) {
			finishAndThanks();
		} else if (item.getItemId() == 4) {
			showDialog(2);
		} else if (item.getItemId() == 3) {
			finish();
			Intent intent = new Intent();
			intent.setClass(this, SettingActivity.class);
			startActivity(intent);
		} else if (item.getItemId() == 2) {
			if (Prop.isNightMode()) {
				Prop.setNightMode(false);
			} else {
				Prop.setNightMode(true);
			}
			title = (TextView) findViewById(R.id.title);
			fresh = (ImageView) findViewById(R.id.fresh);
			fresh.setOnClickListener(new FreshListener());

			getInfo(false);
		} else {
			getInfo(true);
		}
		return super.onOptionsItemSelected(item);
	}

	private void getInfo(boolean force) {
		
		
		
		if (state == DownloadAsyncTask.UPLOAD_FINISHED) {
			state = DownloadAsyncTask.UPLOADING;
			DownloadAsyncTask task = new DownloadAsyncTask(force);
			task.execute();
		}

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (newsList != null) {
			NewsInfo m = newsList.get(position);
			Intent intent = new Intent();
			intent.putExtra("m", m);
			intent.setClass(RssActivity.this, ReadContentActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			showDialog(1);
			i++;
			return true;

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == 1) {
			return getExitDialog();
		}
		if (id == 2) {
			return getAboutDialog();
		}
		if (id == 3){
			return getWhatsNewDialog();
		}
		return null;
	}
	/**
	 * 生成“新功能”对话框
	 * @return
	 */
	private Dialog getWhatsNewDialog() {
		Dialog dialog;
		Builder builder = new android.app.AlertDialog.Builder(this);
		builder.setTitle("1.2版本更新日志")
				.setMessage(
								  "        感谢您下载本应用，欢迎来到1.2版本。\n\n"
								+ "这一版本新增功能有：\n\n"
								+ "1.  新增设置页，可自定义程序开关\n"
								+ "2.  在阅读新闻和评论界面添加音量翻页功能\n"
								+ "3.  新增图片开关，用户可以根据需要开关，关闭图片开关即可实现0流量离线阅读\n"
								+ "4.  更新上帝模式入口（上版本有一哥们就进入了，还在下面留了言）\n"
								+ "5.  加入关于和更新日志对话框");
		dialog = builder.create();
		return dialog;
	}

	/**
	 * 生成“关于”对话框
	 * 
	 * @return
	 */
	private Dialog getAboutDialog() {
		Dialog dialog;
		Builder builder = new android.app.AlertDialog.Builder(this);
		builder.setTitle("关于  CnBeta version:1.2")
				.setMessage(
						"        感谢您下载本应用，相信您和我一样是西贝的忠实粉丝。\n"
								+ "        我要告诉您的是，写这个软件人是个苦逼的屌丝，靠着广告费当做零花钱，您是不是想到了昆明loser程序员呢？\n"
								+ "        所以，请不要反感屌丝不知廉耻的投放广告，如果可以，帮忙点两下码农就感激不尽了....\n"
								+ "        虽然这样，既然您对我的软件如此关注，就告诉您一个秘密吧：每个版本里面都有一个\"上帝模式\"，进入后可以享受无广告干扰的阅读体验，这个版本您找到了么？\n"
								+ "        请关注http://apk.gfan.com/Product/App267130.html吧，相信您能在这和大家一起找到答案");
		dialog = builder.create();
		return dialog;
	}

	/**
	 * 生成“确实退出”对话框
	 * 
	 * @return
	 */
	private Dialog getExitDialog() {
		Dialog dialog;
		Builder builder = new android.app.AlertDialog.Builder(this);
		// 设置对话框的图标
		// 设置对话框的标题
		builder.setTitle("退出").setMessage("真的要退出么？")
				// 添加按钮，android.content.DialogInterface.OnClickListener.OnClickListener
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						RssActivity.this.finishAndThanks();

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});

		// 创建一个列表对话框
		dialog = builder.create();
		return dialog;
	}

	public void finishAndThanks() {
		// Intent intent = new Intent();
		// intent.setClass(this, WelcomeActivity.class);
		// startActivity(intent);
		finish();
	}



	class DownloadAsyncTask extends AsyncTask<Void, Void, Void> {

		public static final int UPLOAD_FINISHED = 1;
		public static final int UPLOADING = 0;
		public static final int READ_FROM_BUFFER = -1;
		public static final int FRESH_LIST = 100;

		public static final int NEW_MSG = 0;
		public static final int READED = 1;

		public final static int MAX_UPLOAD_NUM = 20;

		private final static String RSS_URL = "http://rssdiy.com/rss.php?img&drt";

		private ArrayList<NewsInfo> temp;
		private boolean force = false;

		private List<HashMap<String, String>> list;

		public DownloadAsyncTask(boolean force) {
			this.force = force;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (Prop.isChangedNightMode()) {
				Prop.setChangedNightMode(false);
			}

			if (RssActivity.state == UPLOAD_FINISHED) {
				Toast.makeText(RssActivity.this, "更新完成", Toast.LENGTH_SHORT)
						.show();
			}
			if (RssActivity.state == READ_FROM_BUFFER) {
				if (!readFromSD()) {
					Toast.makeText(RssActivity.this, "在您机器上没有缓存新闻",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(RssActivity.this, "更新失败,请检查网络，从缓存读取数据...",
							Toast.LENGTH_SHORT).show();
				}
			}
			RssActivity.state = UPLOAD_FINISHED;
			pack();
			refreshList(list);
			RssActivity.newsList = temp;
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			if (!Prop.isChangedNightMode()) {
				Toast.makeText(RssActivity.this, "开始拉取新闻，请稍等...",
						Toast.LENGTH_SHORT).show();
			}
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			synchronized (this) {
				if (readFromSD() == false || force == true) {
					System.out.println("enter");
					try {

						analysis();
						write2SD();
						RssActivity.state = UPLOAD_FINISHED;
					} catch (Exception e) {
						RssActivity.state = READ_FROM_BUFFER;
						// Toast.makeText(rssActivity,
						// "更新失败,请检查网络，从缓存读取数据...",Toast.LENGTH_SHORT).show();
						// readFromSD();
						e.printStackTrace();
					}

				}
			}
			return null;
		}

		/**
		 * 从网络下载、解析xml，并存放在newsList里
		 * 
		 * @throws Exception
		 */
		private void analysis() throws Exception {
			temp = new ArrayList<NewsInfo>();

			SAXReader reader = new SAXReader();
			// Document doc = reader.read(new File(sdroot + "/1.txt"));
			Document doc = reader.read(new URL(RSS_URL));
			List<Node> list = doc.selectNodes("/rss/channel/item");

			// int i = 0;
			for (Node node : list) {
				NewsInfo news = new NewsInfo();

				String title = node.selectSingleNode("title").getText();
				title = title.replaceAll("&#34;", "\"");
				title = title.replaceAll("&#38;quot;", "\"");

				news.setTitle(title);
				news.setLink(new URL(node.selectSingleNode("link").getText()));

				// String str = node.selectSingleNode("description").getText();
				String str = node.selectSingleNode("description").getText();
				// String[] s = str.split("<img");
				// s[0].replaceAll("<.*>", "");

				//

				news.setDescription(str);
				news.setCategory(node.selectSingleNode("category").getText());
				news.setPubDate(new Date(node.selectSingleNode("pubDate")
						.getText()));
				news.setNewsState(0);
				temp.add(news);

			}

		}

		/**
		 * 将newsList对象卸载sd卡中，实现离线阅读
		 * 
		 * @throws Exception
		 */
		private void write2SD() throws Exception {

			ObjectOutputStream oos = new ObjectOutputStream(
					new FileOutputStream(new File(Prop.SDRoot + "/2.txt")));
			oos.writeObject(temp);
			oos.flush();

		}

		/**
		 * 从sd卡中读取newsList数据
		 * 
		 * @return
		 */
		private boolean readFromSD() {
			ObjectInputStream ois;
			try {
				ois = new ObjectInputStream(new FileInputStream(new File(
						Prop.SDRoot + "/2.txt")));

				temp = (ArrayList<NewsInfo>) ois.readObject();

				return true;
			} catch (Exception e) {
				return false;
			}
		}

		/**
		 * 打包更新列表所需的数据
		 */
		private void pack() {
			list = new ArrayList<HashMap<String, String>>();
			List<NewsInfo> remove = new ArrayList<NewsInfo>();
			for (NewsInfo m : temp) {
				HashMap<String, String> map = new HashMap<String, String>();

				map.put("title", m.getTitle());
				map.put("pubDate", m.getPubDate().toLocaleString());

				String s = spiltText(m);
				if (s == null || s.length() == 0) {
					remove.add(m);
					continue;
				}

				if (s.length() > 110) {
					map.put("description", s.substring(0, 110) + "...");
				} else {
					map.put("description", s);
				}

				list.add(map);
			}

			for (NewsInfo newsInfo : remove) {
				temp.remove(newsInfo);
			}

		}

		/**
		 * 实现UI的更新
		 * 
		 * @param list
		 */
		private void refreshList(List<HashMap<String, String>> list) {
			SimpleAdapter simpleAdapter = new SimpleAdapter(RssActivity.this, list,
					Prop.newsListLayout, new String[] { "title", "pubDate",
							"description" }, new int[] { R.id.title,
							R.id.pubDate, R.id.description });

			RssActivity.this.setListAdapter(simpleAdapter);
		}

		private String spiltText(NewsInfo m) {
			String str = m.getDescription();

			str = str.replaceAll("<.*?>", "");
			str = str.replaceAll("\r", "");
			str = str.replaceAll("\n", "");
			str = str.replaceAll("&nbsp", "");
			str = str.replaceAll(";", "");
			str = str.replaceAll("    *", "");

			return str;
		}

	}
}